package com.msmall.community.dpt.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.common.CascadeCollection;
import com.msmall.community.dpt.dao.DepartmentDao;
import com.msmall.community.dpt.model.Department;
import com.msmall.community.dpt.service.DepartmentManager;
import com.msmall.community.user.service.UserManager;

public class DepartmentManagerImpl extends BaseManagerImpl<Department, Long> implements DepartmentManager{

	private static final Log log = LogFactory.getLog(DepartmentManagerImpl.class);
	
	private DepartmentDao departmentDao;
	
	private UserManager userManager;

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	/**
	 * 创建新的栏目
	 * @param userid creator
	 * @return
	 */
	public Department saveDepartment(Department department,Long userid) throws Exception{
		try{
			if(department.getParentid() == null){
				department.setParentid(ConstantDB.CASCADE_ID_TOP);
			}
			department.setUserid(userid);
			department.setCreateTime(new Date());
			department = (Department) departmentDao.saveObject(department);
			return department;
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	
	/**
	 * 刷新所有数据到缓存
	 */
	public void refresh()throws Exception{
		try{
			List<Department> allDatas = departmentDao.getAll(Department.class);
			if(allDatas == null || allDatas.size() == 0)
				return;
			CascadeCollection<Department> cs = new CascadeCollection<Department>();
			cs.parser(allDatas, "departmentid", "parentid", "orders", CascadeCollection.ORDERS_ASC);
			CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).put(Constants.CACHE_KEY_DEPARTMENT_CASCADECOLLECTION, cs);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
}
